package ua.naiksoftware.stompclientexample;

import ohos.agp.components.*;
import ohos.agp.window.service.Display;
import ohos.agp.window.service.DisplayManager;
import ohos.app.Context;

import java.util.Collections;
import java.util.List;

/**
 * Created by Naik on 24.02.17
 *
 * @since 2021-04-27
 */
public class SimpleAdapter extends BaseItemProvider {
    private static final int NUM = 25;
    private List<String> data;
    private Context mContext;
    private Display display;

    /**
     * 构造函数
     * *
     *
     * @param list
     * @param context
     */
    public SimpleAdapter(List<String> list, Context context) {
        this.data = list;
        this.mContext = context;
        display = DisplayManager.getInstance().getDefaultDisplay(context).get();
    }

    /**
     * getCount
     *
     * @return int
     */
    @Override
    public int getCount() {
        return data == null ? 0 : data.size();
    }

    /**
     * getItem
     *
     * @param position position
     * @return Object
     */
    @Override
    public Object getItem(int position) {
        if (data != null && position >= 0 && position < data.size()) {
            return data.get(position);
        }
        return Collections.emptyList();
    }

    /**
     * getItemId
     *
     * @param position position
     * @return long
     */
    @Override
    public long getItemId(int position) {
        return position;
    }

    /**
     * getComponent
     *
     * @param position           position
     * @param convertComponent   convertComponent
     * @param componentContainer componentContainer
     * @return Component
     */
    @Override
    public Component getComponent(int position, Component convertComponent, ComponentContainer componentContainer) {
        ViewHolder holder = new ViewHolder();
        if (convertComponent == null) {
            convertComponent = LayoutScatter.getInstance(mContext).parse(ResourceTable.Layout_item_layout, null, true);
            if (convertComponent != null) {
                holder.title = (Text) convertComponent.findComponentById(ResourceTable.Id_text);
                convertComponent.setTag(holder);
            }
        } else {
            holder = (ViewHolder) convertComponent.getTag();
        }
        holder.title.setHeight(display.getAttributes().height / NUM);
        holder.title.setText(data.get(position));
        return convertComponent;
    }

    /**
     * ViewHolder
     *
     * @since 2021-04-27
     */
    private static class ViewHolder {
        private Text title;

        public Text getTitle() {
            return title;
        }

        public void setTitle(Text text) {
            this.title = text;
        }
    }
}
